/* SPI interface commands */

/* Copyright (C) 2009-2011 David Zanetti
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; version 2 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

/* This implements the setup/use of the hardware SPI interface
   but does not handle the !CS line of any SPI-connected chip. */

#include <avr/io.h>
#include <avr/pgmspace.h>
#include <stdio.h>
#include <avr/eeprom.h>

#include "global.h"
#include <util/delay.h>

#include "spi.h"
#include "serial.h"

void spi_init(void) {
	/* initalise the only SPI port as a master */
	SPIDDR |= ((1 << MOSI) | (1 << SCK)); /* Master Out, SPI Clock, as outputs */
	SPSR |= (1 << SPI2X);
	SPCR = (1 << SPE) | (1 << MSTR); /* SPI On, Master, f/2 clock */
}

uint8_t spi_txrx(uint8_t c) {
	uint8_t in;

#if defined(DEBUG_SPI)
	serial0_tx_PGM(PSTR("spi: "));
	serial0_tx_hex(c);
#endif

	SPDR = c;
	while (!(SPSR & (1 << SPIF)));
	in = SPDR;

#if defined(DEBUG_SPI)
	serial0_tx_PGM(PSTR(" "));
	serial0_tx_hex(in);
	serial0_tx_cr();
#endif

	return in;
}


